package com.css.apps.base.user.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.css.apps.base.common.Constants;
import com.css.apps.base.common.provider.UserQueryProvider;
import com.css.apps.base.common.util.MenuUtil;
import com.css.apps.base.user.leader.model.LeaderSecretary;
import com.css.apps.base.user.model.SUser;
import com.css.core.configuration.Environment;
import com.css.db.memcached.MemCachedFactory;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.DateUtil;
import com.css.util.StringHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class UserHelper {

	/**
	 * 当登录失败的时候更新最后登录时间以及失败次数，登录成功后失败次数清零
	 * 
	 * @author liuzhb on Jan 9, 2014 4:45:12 PM
	 */
	public void updateFailedLoginCount(SUser sUser) {
		if (sUser != null) {
			TransactionCache tc = new TransactionCache();
			sUser.setFailedLoginCount(sUser.getFailedLoginCount() + 1);
			tc.update(sUser);
			tc.commit();
		}
	}
	
	/**
	 * 获取登录失败次数 用户ID查询优化 ( by shenhc)(2014-09-28)
	 * 
	 * @author liuzhb on Jan 9, 2014 5:00:15 PM
	 * @param loginName
	 */
	public SUser getFailedLoginCount(String loginName) {
		String userId = getUserIdByName(loginName);
		if (StringHelper.isNotEmpty(userId)) {
			SUser sUser = QueryCache.get(SUser.class, userId);
			if (sUser != null) {
				// 如果当前日期与用户最后登录日期不在同一天，则登录失败次数清零
				if (sUser.getLastLoginTime() != null) {
					boolean flag = DateUtil.compareDate(sUser.getLastLoginTime(), Calendar.getInstance().getTime());
					if (flag == false) {
						TransactionCache tc = new TransactionCache();
						sUser.setFailedLoginCount(0);
						sUser.setLastLoginTime(Calendar.getInstance().getTime());
						tc.update(sUser);
						tc.commit();
					}
				}
				return sUser;
			}
		}
		return null;
	}
	
	private String getUserIdByName(String loginName) {
		if (StringHelper.isEmpty(loginName))
			return null;
		String key = null;
		try {
			key = com.css.util.Md5Util.getMD5(Constants.USER_ID_CACHE_NAME + loginName.trim());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (key == null)
			return null;
		String userId = (String) com.css.db.memcached.MemCachedFactory.get(key);
		if (StringHelper.isEmpty(userId)) {
			QueryCache qc = new QueryCache(
					"select a.uuid from SUser a where a.loginName=:loginName and a.delFlag=:delFlag")
							.setParameter("delFlag", Environment.UN_DELETE_STATE).setParameter("loginName", loginName);
			userId = (String) qc.uniqueResult();
			if (userId != null) {
				com.css.db.memcached.MemCachedFactory.set(key, userId);
			}
		}
		return userId;
	}

	/// 清除菜单缓存
	public void clearUserMenuCache(String userId) {
		SUser user = UserQueryProvider.getUser(userId);
		if (user == null) {
			return;
		}
		// 缓存同步
		String key = MenuUtil.getUserKey(user);
		MemCachedFactory.delete(key);
	}
	
	public List<LeaderSecretary> getLeaderSecretary(String leaderId, String secretaryJson) {
		if (StringHelper.isAnyEmpty(leaderId, secretaryJson)) {
			return null;
		}
		JSONArray arr = JSONArray.fromObject(secretaryJson);
		Calendar c = Calendar.getInstance();
		SUser leader = UserQueryProvider.getUser(leaderId);
		List<LeaderSecretary> lsList = new ArrayList<>();
		
		for (Object o : arr) {
			JSONObject item = (JSONObject) o;
			LeaderSecretary ls = new LeaderSecretary();
			ls.setCreateTime(c.getTime());
			ls.setLeaderDeptId(leader.getOrgId());
			ls.setLeaderId(leaderId);
			ls.setLeaderName(leader.getRealName());
			ls.setOrderNum(0);
			ls.setSecretaryId(item.getString("secretaryId"));
			ls.setSecretaryName(item.getString("secretaryName"));
			ls.setSecretaryDeptId(item.getString("secretaryDeptId"));
			ls.setLeaderBranchDeptId(item.getString("branchDeptId"));
			ls.setLeaderBranchDeptName(item.getString("branchDeptName"));
			ls.setUpdTime(c.getTime());
			lsList.add(ls);
		}
		return lsList;
	}
	
}
